#include <event2/event.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

//#define USE_DEBUG
static void discard_cb(int severity, const char* msg)
{
    /* This callback does nothing.*/
}
static FILE* logfile = NULL;
static void write_to_file_cb(int severity, const char* msg)
{
    const char* s;
    printf("%s:%d\n",__FUNCTION__,__LINE__);
    if (!logfile)
        return;
    switch (severity) {
        case _EVENT_LOG_DEBUG: s = "debug"; break;
        case _EVENT_LOG_MSG: s = "msg"; break;
        case _EVENT_LOG_WARN: s = "warn"; break;
        case _EVENT_LOG_ERR: s = "error"; break;
        default: s = "?"; break; /* never reached*/
    }
    fprintf(logfile, "[%s] %s\n", s, msg);
}
/* Turn off all logging from Libevent.*/
void suppress_logging(void)
{
    event_set_log_callback(discard_cb);
}
/* Redirect all Libevent log messages to the C stdio file ’f’.*/
void set_logfile(FILE* f)
{
    logfile = f;
    event_set_log_callback(write_to_file_cb);
}

void cb_func(evutil_socket_t fd, short what, void* arg)
{
    const char* data = arg;
    printf("Got an event on socket %d:%s%s%s%s [%s]\n",
        (int) fd,
        (what&EV_TIMEOUT) ? " timeout" : "",
        (what&EV_READ) ? " read" : "",
        (what&EV_WRITE) ? " write" : "",
        (what&EV_SIGNAL) ? " signal" : "",
        data);
}
void main_loop(evutil_socket_t fd1, evutil_socket_t fd2)
{
    struct event* ev1, * ev2;
    struct timeval five_seconds = {5,0};
    struct event_base* base = event_base_new();
    /* The caller has already set up fd1, fd2 somehow, and make them nonblocking.*/
    ev1 = event_new(base, fd1, EV_TIMEOUT|EV_READ|EV_PERSIST, cb_func,(char * )"Reading event");
    ev2 = event_new(base, fd2, EV_TIMEOUT|EV_PERSIST, cb_func,(char * )"Writing event");
    event_add(ev1, &five_seconds);
    event_add(ev2, NULL);
    event_base_dispatch(base);
}
int main()
{
    // FILE *f=fopen("logTest.txt","w");
    // if(f==NULL)
    //     exit(-1);
    // set_logfile(f);
    //event_debug("event_add:vsdvsdvsdvsv");
    main_loop(fileno(stdin),fileno(stdout));
    return 0;
}